// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129

const db = uniCloud.database();
const dbactivity = db.collection('activity');
const dbcheckin = db.collection('checkin');

module.exports = {

	async getAllActivities(event) {
		const res = await dbactivity.where({
			isSave: true
		}).orderBy("date", "asc").orderBy("timeRange.start", "asc").get()
		if (res.data) {
			return {
				code: 0,
				data: res.data
			}
		} else {
			return {
				code: -1,
				message: '没有活动数据'
			}
		}
	},

	/**
	 * 分页+模糊搜索活动（支持名称、日期、时间），在status=0的基础上进行搜索
	 * @param {Object} event
	 * @param {string} [event.keyword] 搜索关键词
	 * @param {number} [event.page=1] 当前页码
	 * @param {number} [event.limit=10] 每页数量
	 */
	async searchActivities(event) {
		const {
			keyword = "", page = 1, limit = 10
		} = event;
		const skip = (page - 1) * limit;

		// 1. 定义基础查询条件，始终包含 status: 0
		let whereCondition = {
			isSave: true
		};

		// 2. 如果存在关键词，则在基础查询上增加 $or 模糊匹配条件
		if (keyword.trim() !== "") {
			const regexStr = keyword.trim(); // 关键词字符串
			const options = "i"; // 不区分大小写
			whereCondition.$or = [{
					$expr: {
						$regexMatch: {
							input: "$name",
							regex: regexStr,
							options: options
						}
					}
				},
				{
					$expr: {
						$regexMatch: {
							input: "$date",
							regex: regexStr,
							options: options
						}
					}
				},
				{
					$expr: {
						$regexMatch: {
							input: "$locationName",
							regex: regexStr,
							options: options
						}
					}
				},
				{
					$or: [{
							$expr: {
								$regexMatch: {
									input: "$timeRange.start",
									regex: regexStr,
									options: options
								}
							}
						},
						{
							$expr: {
								$regexMatch: {
									input: "$timeRange.end",
									regex: regexStr,
									options: options
								}
							}
						}
					]
				}
			];
		}

		// 3. 将组合后的查询条件应用到查询中
		const query = dbactivity.where(whereCondition);

		// 获取总数
		const countRes = await query.count();
		const total = countRes.total;

		// 排序 + 分页
		const dataRes = await query
			.orderBy("date", "desc")
			.orderBy("timeRange.start", "asc")
			.skip(skip)
			.limit(limit)
			.get();

		if (dataRes.data && dataRes.data.length > 0) {
			return {
				code: 0,
				data: dataRes.data,
				total: total
			};
		} else {
			return {
				code: -1,
				message: "没有匹配数据"
			};
		}
	},

	async getActivitiesById(event) {
		const res = await dbactivity.where({
			_id: event._id
		}).get()
		if (res.data) {
			return {
				code: 0,
				message: '查询成功',
				data: res.data
			}
		} else {
			return {
				code: -1,
				message: '没有活动数据'
			}
		}
	},

	async createActivity(event) {
		const res = await dbactivity.add(event)
		if (res.id) {
			return {
				code: 0,
				message: '活动创建成功',
				data: {
					_id: res.id
				}
			}
		} else {
			return {
				code: 500,
				message: '活动创建失败'
			}
		}
	},

	async updateActivity(event) {
		try {
			// 参数校验
			if (!event?._id) {
				return {
					code: -2,
					message: '缺少车辆预约ID参数'
				};
			}
			if (!event?.data || typeof event.data !== 'object' || Object.keys(event.data).length === 0) {
				return {
					code: -3,
					message: '更新数据不能为空且必须为对象格式'
				};
			}

			// 执行更新操作
			const updateResult = await dbactivity
				.doc(event._id)
				.update(event.data);

			// 处理更新结果
			if (updateResult.updated === 0) {
				return {
					code: 1,
					message: '数据未发生变更',
					updatedId: event._id
				};
			}

			return {
				code: 0,
				message: '数据更新成功',
				updatedId: event._id,
				affected: updateResult.updated,
				timestamp: new Date().toISOString()
			};
		} catch (error) {
			return {
				code: 0,
				message: error.message
			};
		}
	},

	async getCheckinRecord(event) {
		const res = await dbcheckin.where(event).get()
		return {
			code: 0,
			message: '查询成功',
			data: res.data
		}
	},

	async addCheckinRecord(event) {
		const {
			activityId,
			userid
		} = event;
		try {

			// 查询是否已有该用户的签到记录
			const existingRecord = await dbcheckin
				.where({
					activityId: activityId,
					userid: userid
				})
				.limit(1)
				.get();
			if (existingRecord.data && existingRecord.data.length > 0) {
				return {
					code: -1,
					message: '该用户已在当前活动中签到过'
				};
			}
			// 插入签到记录
			const res = await dbcheckin.add(event);
			return {
				code: 0,
				message: '签到成功',
				data: res
			};
		} catch (err) {
			return {
				code: -1,
				message: '签到失败',
				error: err
			};
		}
	},

	_before: function() { // 通用预处理器

	}
}